Passed
Push — dev ( dc7ede...6b529c )
by Kasper
05:04 queued 01:55
created

Map.tsx ➔ Map   C

Complexity

Conditions 7

Size

Total Lines 175
Code Lines 123

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 123
dl 0
loc 175
rs 5.6
c 0
b 0
f 0
cc 7

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import { useState, useEffect } from 'react';
2
import { ScrollView, Image, Text, View, StyleSheet, StatusBar, Button, Pressable, InteractionManagerStatic } from 'react-native';
3
import MapView, { Marker, Circle, Polygon } from 'react-native-maps';
4
import * as Location from 'expo-location';
5
import React from 'react';
6
import mapModel from '../models/map';
7
import scooterModel from '../models/scooter';
8
import {API_KEY} from "@env";
9
import config from '../config/config.json';
10
import Icon from 'react-native-vector-icons/Octicons';
11
import ScooterModal from './modals/ScooterModal';
12
import NavBar from './drawer/NavBar';
13
import ZoneModal from './modals/ZoneModal';
14
import ScanScreen from './modals/QrScanner';
15
import QRCodeScanner from 'react-native-qrcode-scanner';
16
import QrScanner from './modals/QrScanner';
17
import JourneyModal from './modals/JourneyModal';
18
19
const marker = require('../assets/scooter_white.png');
20
const selectedMarker = require('../assets/scooter_blue.png');
21
22
function markerIcon(index, selected) {
23
    if (index === selected) {
24
        return selectedMarker;
25
    }
26
    return marker;
27
};
28
29
export default function Map({navigation, API_KEY, position, setPosition, token}): any {
30
    const [locationMarker, setLocationMarker] = useState(null);
31
    const [currentCity, setCurrentCity] = useState(null);
32
    const [zones, setZones] = useState([]);
33
    const [scooters, setScooters] = useState([]);
34
    const [currentScooter, setCurrentScooter] = useState(null);
35
    const [modalVisible, setModalVisible] = useState(false);
36
    const [zoneModalVisible, setZoneModalVisible] = useState(false);
37
    const [currentZone, setCurrentZone] = useState(null);
38
    const [cameraVisible, setCameraVisible] = useState(false);
39
    const [journeyModal, setJourneyModal] = useState(false);
40
    const [toggleTimer, setToggleTimer] = useState(false);
41
    const [markerSelected, setMarkerSelected] = useState(null);
42
        
43
    /**
44
     * Set user position
45
     */
46
    useEffect(() => {
47
        async function fetchPosition(): Promise<void> {
48
            const { status } = await Location.requestForegroundPermissionsAsync();
49
50
            // if (status !== 'granted') {
51
            //     setErrorMessage('Permission to access location was denied');
52
            //     return;
53
            // }
54
55
            const currentLocation = await Location.getCurrentPositionAsync({});
56
57
            const userCoordinates = {
58
                //latlang hardcoded for testing
59
                latitude: currentLocation.coords.latitude,
60
                longitude: currentLocation.coords.longitude
61
                // latitude: 56.161013580817986,
62
                // longitude: 15.587742977884904
63
            };
64
65
    
66
            setPosition(userCoordinates);
67
            
68
            mapModel.getClosestCity(position);
69
70
            setLocationMarker(<Marker
71
                coordinate={{
72
                    //latlang hardcoded for testing
73
                    // latitude: currentLocation.coords.latitude,
74
                    // longitude: currentLocation.coords.longitude
75
                    latitude: 56.161013580817986,
76
                    longitude: 15.587742977884904
77
                }}
78
                title="My location"
79
                pinColor="blue"
80
                flat={false}
81
            />);
82
        };
83
84
85
        fetchPosition();
86
87
    }, []);
88
89
    /**
90
     * Set city to city that is closest to user and zones for that city
91
     */
92
    useEffect(() => {
93
        async function setUpMap(): Promise<void> {
94
            const city = await mapModel.getClosestCity(position);
95
            
96
            
97
            // Set city that is closest to user
98
            setCurrentCity(city);
99
                        
100
            /**
101
             * Set zones on map
102
             */
103
            const zones = mapModel.getZones(city);
104
            setZones(zones);
105
106
        };
107
        setUpMap();
108
    }, []);
109
110
    /**
111
     * Get scooters for current city,
112
     * Updated every 5 seconds
113
     */
114
    useEffect(() => {
115
        const interval = setInterval(() => {
116
117
            // Get scooters
118
            async function getScooters() {
119
                const city = await mapModel.getClosestCity(position);
120
                
121
                const result = await scooterModel.getScooters(city); 
122
                
123
                if (result) {
124
                    const scooters = result['cityScooters'];
125
                    
126
                    const sortedScooters = scooterModel.sortAvailableScooters(scooters);
127
                    setScooters(sortedScooters);
128
                };
129
130
            };
131
132
      
133
            getScooters();
134
135
        }, 5000);
136
        return () => clearInterval(interval);
137
      }, []);
138
139
140
    return (
141
        <View style={styles.container}>
142
            <MapView
143
                style={styles.map}
144
                initialRegion={{
145
                    latitude: position.latitude? position.latitude : 56.161013580817986,
146
                    longitude: position.longitude? position.longitude : 15.587742977884904,
147
                    latitudeDelta: 0.03,
148
                    longitudeDelta: 0.03,
149
                }}
150
                userInterfaceStyle={'dark'}
151
            >
152
                {locationMarker}
153
154
                {scooters.map((s, index) => 
155
                    <Marker
156
                        coordinate={s['coordinates']}
157
                        icon={markerIcon(index, markerSelected)}
158
                        tappable={true}
159
                        key={index}
160
                        onPress={() => {
161
                            setCurrentScooter(s);
162
                            setModalVisible(true);
163
                            setMarkerSelected(index);                            
164
                        }}
165
                        >
166
                    </Marker>
167
                )}
168
                {zones.map((z, index) => (                    
169
                    <Polygon 
170
                        coordinates={z['coordinates']}
171
                        strokeColor={z['zoneColor']}
172
                        strokeWidth={3}
173
                        fillColor={z['zoneColor']}
174
                        key={index}
175
                        tappable={true}
176
                        onPress={() => {
177
                            setCurrentZone(z)
178
                            setZoneModalVisible(true)                            
179
                        }}
180
                    />
181
                ))}
182
            </MapView>
183
184
            <ScooterModal navigation={navigation} scooter={currentScooter} modalVisible={modalVisible} currentCity={currentCity} setModalVisible={setModalVisible} setJourneyModal={setJourneyModal} setToggleTimer={setToggleTimer} position={position}/> 
185
186
            <ZoneModal navigation={navigation} zone={currentZone} zoneModalVisible={zoneModalVisible} setZoneModalVisible={setZoneModalVisible} currentCity={currentCity}/>
187
            
188
 
189
            <JourneyModal navigation={navigation} scooter={currentScooter} journeyModal={journeyModal} setJourneyModal={setJourneyModal} toggleTimer={toggleTimer} setToggleTimer={setToggleTimer}/>
190
191
            <Pressable onPress={() => {setCameraVisible(true)}} style={styles.googleLogin}>
192
                    <Icon 
193
                        name='screen-full' 
194
                        size={15} 
195
                        color='white'
196
                    />
197
                    <Text style={styles.googleText}>Scan to unlock</Text>
198
            </Pressable>
199
200
            <NavBar navigation={navigation} />
201
            <QrScanner navigation={navigation} cameraVisible={cameraVisible} setCameraVisible={setCameraVisible} scooter={currentScooter} setModalVisible={setModalVisible} currentCity={currentCity} setCurrentScooter={setCurrentScooter}/>
202
        </View>
203
        
204
    )
205
}
206
207
const styles = StyleSheet.create({
208
    container: {
209
        // flex: 1,
210
        height: '100%',
211
        alignItems: "center",
212
        width: '100%'
213
    },
214
215
    map: {
216
        position: 'absolute',
217
        top: 0,
218
        left: 0,
219
        bottom: 0,
220
        right: 0,
221
    },
222
223
    drawer: {
224
        position: 'absolute',
225
        width: 50,
226
        height: 50, 
227
        left: 50,
228
        backgroundColor: 'white',
229
        marginTop: 50,
230
        borderRadius: 25,
231
        justifyContent: 'center',
232
        alignItems: 'center'
233
    },
234
    
235
    shadowProp: {
236
        elevation: 5,
237
        shadowColor: 'black'
238
    },
239
240
    googleLogin: {
241
        backgroundColor: '#1A1A1A',
242
        width: '65%',
243
        height: 45,
244
        borderRadius: 25,
245
        display: 'flex',
246
        flexDirection: 'row',
247
        justifyContent: 'center',
248
        alignItems: 'center',
249
        marginBottom: 30
250
    },
251
252
    googleText: {
253
        color: 'white',
254
        fontWeight: 'bold',
255
        fontSize: 18,
256
        marginLeft: 10
257
    },
258
259
    googleIcon: {
260
        height: 20,
261
        width: 20
262
    }
263
});
264
265